package Automate;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class Autothread extends Thread {
	
	int etat;
	Autothread copain;
	PipedWriter out;
	PipedReader in;
	
	public Autothread(){
		super();
		
		this.out = new PipedWriter();
		
		etat = 0;
	}
	
	/**
	 * Envoi un message au client
	 * @param s
	 */
	public void send(String s){
		try {
			out.flush();
			out.write(s+';');
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Recevoir un message
	 * @param s
	 */
	public String receive(){
		char c = '$';
		String message = "";
		// ; caractere de fin de message
		while(c != ';'){
			message += c;
			
			try {
				c = (char) in.read();
			} catch (IOException e) {e.printStackTrace();}
			
		}

		message = message.substring(1);
		
		return message;
	}
	
	public void setCopain(Autothread c){
		this.copain = c;
		try {
			this.in = new PipedReader(copain.getPipedOut());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private PipedWriter getPipedOut() {
		return out;
	}
	


	public int getEtatCurrent() {
		return this.etat;
	}

}
